package com.gitee.chessboard.scan;

import com.gitee.chessboard.scan.discern.DiscernHandler;

import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 扫描管理类
 *
 * @author 敲代码的旺财
 * @date 2021/12/6 10:18
 */
public class ScanManager {

    private Map<String, ScanHandler> scanHandlerMap;

    private DiscernHandler discernHandler;

    public ScanManager() {
        this.scanHandlerMap = new ConcurrentHashMap<>();
        this.discernHandler = new DiscernHandler();
    }

    /**
     * 扫描指定路径下的资源 支持通配符
     *
     * @param basePackage 指定的资源路径
     * @return 资源集合
     */
    public URL[] scan(String basePackage) {
        ScanHandler scanHandler = scanHandlerMap.get(basePackage);
        if (scanHandler != null) {
            return scanHandler.getUrls();
        }
        return getScanHandler(basePackage).scan();
    }

    /**
     * 创建扫描处理器
     *
     * @param basePackage 指定的资源路径
     * @return 扫描处理器
     */
    public synchronized ScanHandler getScanHandler(String basePackage) {
        ScanHandler scanHandler = scanHandlerMap.get(basePackage);
        if (scanHandler == null) {
            scanHandler = new ScanHandler(basePackage);
            scanHandlerMap.put(basePackage, scanHandler);
        }
        return scanHandler;
    }

    /**
     * 设置扫描器
     *
     * @param basePackage 扫描范围
     * @param scanHandler 扫描器
     */
    public void putScanHandler(String basePackage, ScanHandler scanHandler) {
        scanHandlerMap.put(basePackage, scanHandler);
    }

    /**
     * 识别
     *
     * @param basePackage 识别范围
     */
    public void discern(String basePackage) {
        URL[] scan = scan(basePackage);
        for (URL url : scan) {
            discernHandler.discern(url);
        }
    }

    /**
     * 获取识别器处理器
     *
     * @return 识别器处理器
     */
    public DiscernHandler getDiscernHandler() {
        return discernHandler;
    }

    /**
     * 设置识别器处理器
     */
    public void setDiscernHandler(DiscernHandler discernHandler) {
        this.discernHandler = discernHandler;
    }
}
